package chpt05;
import java.util.Random;

public class GeomUtils {
    public static class Point {
        private double x;
        private double y;

        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
        
        public double getX() {
            return x;
        }

        public double getY() {
            return y;
        }

        public void setX(double x) {
            this.x = x;
        }

        public void setY(double y) {
            this.y = y;
        }

		@Override
		public String toString() {
			return "Point [x=" + x + ", y=" + y + "]";
		}
    }
    // 计算p1和p2之间的距离
    public static double distanceOf(Point p1, Point p2) {
        double dx = p1.x - p2.x;
        double dy = p1.y - p2.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    // 生成n个Point。每个Point中的x,y的取值范围在[min, max]之间
    public static Point[] createPoints(int n, int min, int max) {
    	Random rnd = new Random();
    	int range = max - min + 1;
        Point[] points = new Point[n];
        for (int i = 0; i < n; i++) {
            points[i] = new Point(rnd.nextInt(range)+min, 
            		rnd.nextInt(range)+min);
        }
        return points;
    }
    // 在points中找到离target最近的点
    public static Point findPoint(Point[] points, Point target) {
        Point closest = null;
        double minDistance = Double.MAX_VALUE;
        for (int i = 0; i < points.length; i++) {
            double distance = distanceOf(points[i], target);
            if (distance < minDistance) {
                closest = points[i];
                minDistance = distance;
            }
        }
        return closest;
    }
    
    public static void main(String[] args) {
    	// 创建n个Point，每个Point中的x,y的取值范围在[min, max]之间
    	int n = 5, min = 0, max = 10;
    	
        GeomUtils.Point[] points = GeomUtils.createPoints(n, min, max);
        for (Point point : points) {
			System.out.println(point);
		}
        // 找到离target点最近的点
        // 也可使用Point p = new Point(0.0, 0.0);来创建类类
        GeomUtils.Point x = new GeomUtils.Point(0, 0);
        GeomUtils.Point closest = GeomUtils.findPoint(points, x);
        System.out.println("Target: "+ x);
        System.out.println("The closest: "+closest);
        
	}
}
